package com.yzt.zhuju.permission;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;

import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;

import com.yzt.zhuju.R;
import com.yzt.zhuju.config.AppConfig;
import com.yzt.zhuju.dialog.CenterBaseDialog;
import com.yzt.zhuju.utils.ActivityManagerUtils;
import com.yzt.p_base.permission.RxPermissions;
import com.yzt.p_base.utils.ToastUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import io.reactivex.functions.Consumer;

/**
 * author : bob
 * date   : 2022/12/1
 * desc   : 权限申请的管理类
 */
@SuppressLint("CheckResult")
public class PermissionsUtils {

    private static PermissionsUtils mInstance;

    public static PermissionsUtils getInstance() {
        if (mInstance == null) {
            mInstance = new PermissionsUtils();
        }
        return mInstance;
    }

    public void checkPermission(Activity activity, String[] list, String label, OnCallBackListener listener) {
        List<String> lists = new ArrayList<>();
        Collections.addAll(lists, list);
        checkPermission(activity, lists, label, listener);
    }

    public void checkCallChatPermission(FragmentActivity activity, List<String> list, String label, OnCallBackListener listener) {
        if (list == null) {
            list = new ArrayList<>();
        }
        StringBuffer sb = new StringBuffer();
        sb = getPermissionLabel(activity, list, sb);
        if (sb.toString().endsWith(",")) {
            String content = sb.toString().substring(0, sb.toString().length() - 1);
            sb = new StringBuffer();
            sb.append(content);
            Bundle bundle = new Bundle();
            String extContent = activity.getString(R.string.apply_some_permission_support_some_function, sb.toString(), label);
            bundle.putString("content", extContent);
            PermissionTipDialog fragment = (PermissionTipDialog) CenterBaseDialog.showDialog(activity, PermissionTipDialog.class, bundle);
            List<String> finalList = list;
            fragment.setOnSelectListener(new PermissionTipDialog.OnSelectListener() {
                @Override
                public void select() {
                    new RxPermissions(activity).request(finalList.toArray(new String[finalList.size()])).subscribe(granted -> {
                        if (granted) {
                            if (listener != null) {
                                listener.open(finalList);
                            }
                        } else {
                            StringBuffer sbf = new StringBuffer();
                            sbf = getPermissionLabel(activity, finalList, sbf);
                            if (sbf.toString().endsWith("、")) {
                                String content1 = sbf.toString().substring(0, sbf.toString().length() - 1);
                                sbf = new StringBuffer();
                                sbf.append(content1);
                            }
                            if (listener != null) {
                                listener.notOpen(finalList, sbf.toString());
                            }

                            openPermission(ActivityManagerUtils.getInstance().permissionGetTopActivity(), sbf.toString());
                        }
                    });
                }

                @Override
                public void cancel() {
                    listener.notOpen(finalList, activity.getString(R.string.refuse));
                }
            });
        } else {
            if (listener != null) {
                listener.open(list);
            }
        }
    }

    /**
     * 打开权限
     */
    private void openPermission(FragmentActivity activity, String content) {

        Bundle bundle = new Bundle();
        bundle.putString("content", activity.getString(R.string.video_call_need_some_permission_go_set, content));
        bundle.putInt("type", 1);
        PermissionTipDialog fragment = (PermissionTipDialog) CenterBaseDialog.showDialog(activity, PermissionTipDialog.class, bundle);
        fragment.setOnSelectListener(new PermissionTipDialog.OnSelectListener() {
            @Override
            public void select() {
                start(activity);
            }

            @Override
            public void cancel() {
                fragment.dismissAllowingStateLoss();
            }
        });
    }

    public void checkPermission(Activity activity, List<String> list, String label, OnCallBackListener listener) {
        checkPermission2(activity instanceof FragmentActivity ? (FragmentActivity) activity : ActivityManagerUtils.getInstance().getTopActivity(), list, label, listener);
    }

    public void checkPermission2(FragmentActivity activity, List<String> list, String label, OnCallBackListener listener) {
        if (list == null) {
            list = new ArrayList<>();
        }
        StringBuffer sb = new StringBuffer();
        sb = getPermissionLabel(activity, list, sb);
        if (sb.toString().endsWith(",")) {
            String content = sb.toString().substring(0, sb.toString().length() - 1);
            sb = new StringBuffer();
            sb.append(content);
            Bundle bundle = new Bundle();
            String extContent = activity.getString(R.string.apply_some_permission_support_some_function, sb.toString(), label);
            bundle.putString("content", extContent);

            activity.getString(R.string.not_get_this_permission, content);

            PermissionTipDialog fragment = (PermissionTipDialog) CenterBaseDialog.showDialog(activity, PermissionTipDialog.class, bundle);
            List<String> finalList = list;
            fragment.setOnSelectListener(new PermissionTipDialog.OnSelectListener() {
                @Override
                public void select() {
                    new RxPermissions(activity).request(finalList.toArray(new String[finalList.size()])).subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(Boolean granted) {
                            if (granted) {
                                if (listener != null) {
                                    listener.open(finalList);
                                }
                            } else {
                                StringBuffer sbf = new StringBuffer();
                                //sbf.append("未获得");
                                sbf = getPermissionLabel(activity, finalList, sbf);
                                if (sbf.toString().endsWith("、")) {
                                    String content = sbf.toString().substring(0, sbf.toString().length() - 1);
                                    sbf = new StringBuffer();
                                    sbf.append(content);
                                    sbf.append(activity.getString(R.string.not_get_this_permission, content));
                                }
                                ToastUtil.showMessage(sbf.toString());
                                if (listener != null) {
                                    listener.notOpen(finalList, sbf.toString());
                                }
                            }
                        }
                    });
                }

                @Override
                public void cancel() {
                    listener.notOpen(finalList, activity.getString(R.string.refuse));
                }
            });
        } else {
            if (listener != null) {
                listener.open(list);
            }
        }
    }

    public StringBuffer getPermissionLabel(FragmentActivity activity, List<String> list, StringBuffer sb) {
        for (int i = 0; i < list.size(); i++) {
            boolean b = lacksPermission(AppConfig.context, list.get(i));
            if (!b) {
                switch (list.get(i)) {
                    case Manifest.permission.MODIFY_AUDIO_SETTINGS:
                        sb.append(activity.getString(R.string.permission_modify_audio_setting));
                        break;
                    case Manifest.permission.WRITE_EXTERNAL_STORAGE:
                        sb.append(activity.getString(R.string.permission_write_external_storage));
                        break;
                    case Manifest.permission.READ_EXTERNAL_STORAGE:
                        sb.append(activity.getString(R.string.permission_read_external_storage));
                        break;
                    case Manifest.permission.CAMERA:
                        sb.append(activity.getString(R.string.permission_camera));
                        break;
                    case Manifest.permission.RECORD_AUDIO:
                        sb.append(activity.getString(R.string.permission_record_audio));
                        break;
                    case Manifest.permission.READ_PHONE_STATE:
                        sb.append(activity.getString(R.string.permission_read_phone_state));
                        break;
//                    case Manifest.permission.ACCESS_COARSE_LOCATION:
//                    case Manifest.permission.WRITE_CONTACTS:
//                        sb.append(activity.getString(R.string.permission_write_contacts));
//                        break;
//                    case Manifest.permission.READ_CONTACTS:
//                        sb.append(activity.getString(R.string.permission_read_contacts));
//                        break;
                    default:
                        break;
                }
            }
        }
        return sb;
    }

    /**
     * 判断是否缺少权限
     */
    public boolean lacksPermission(Context ctx, String permission) {
        return ContextCompat.checkSelfPermission(ctx, permission) != PackageManager.PERMISSION_DENIED;
    }

    //跳转
    public void start(Activity activity) {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.setData(Uri.parse("package:" + activity.getPackageName()));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        activity.startActivity(intent);
    }

    public interface OnCallBackListener {

        void open(List<String> list);

        void notOpen(List<String> list, String label);
    }
}
